import time
import unittest

import jinja2
from flask import Flask, render_template, request, send_from_directory, jsonify, redirect, url_for,session
import os

from Base.BaseSetings import Templates_DIR, USERNAME, PASSWORD, Report_dir
from Base.DataBase import mysqldb
from Base.PublicFunction import render_tem
from TestCase import testcase_sun
from TestCase.testcase_sun import TestWoniuBoss
from Write_Report.Report_Collect import DataCollect
from Write_Report.collect_report_data import collect_report_data

app = Flask(__name__)
app.secret_key="sdjfaklshgkldahgajkagjhsklhdklhkl"

app.config['UPLOAD_FOLDER'] = os.getcwd()
download_floder = app.config['UPLOAD_FOLDER'] + '/upload'



def JJxuanran_render3(result):#template_name, output_file=None, **template_vars
    """ 用jinja2渲染html"""
    env = jinja2.Environment(
        loader=jinja2.FileSystemLoader(Templates_DIR),   #模板的文件路径 +"\\"
        extensions=(),
        autoescape=True
    )
    #通过loader传入的目录 找到目录下的 template_name
    template = env.get_template("ShowExcel.html")  # 模板
    html = template.render(result=result)
    with open(Templates_DIR+"excel.html", 'w', encoding='UTF-8') as f:
        f.write(html)


def allow_file(filename):
    allow_list = ['png', 'PNG', 'jpg', 'doc', 'docx', 'txt', 'pdf', 'PDF','xlsx', 'xls', 'rar', 'exe', 'md', 'zip']
    a = filename.split('.')[1]
    if a in allow_list:
        return True
    else:
        return False


@app.route('/login',methods = ['GET','POST'])
def login():
    if request.method == 'GET':
        return render_template('index/login.html')
    else:
        username = request.form.get('username')
        if username == USERNAME:
            password = request.form.get('password')
            if password == PASSWORD:
                session['username'] = username
                return redirect(url_for("home"))
            else:
                return render_template('index/login.html',errmsg = '密码错误')
        else:
            return render_template('index/login.html',errmsg = '用户名错误')

@app.route('/main',methods=["GET","POST"])
def home():
    return render_template('index.html')


@app.route('/getlist')
def getlist():
    file_url_list = []
    file_floder = app.config['UPLOAD_FOLDER'] + '/upload'

    file_list = os.listdir(file_floder)

    for filename in file_list:
        file_url = url_for('download', filename=filename)
        file_url_list.append(file_url)
    return jsonify(file_list)  #???

@app.route('/download/<filename>')
def download(filename):
    return send_from_directory(download_floder, filename, as_attachment=True)

#数据采集类
class Exc_datacollect():
    Excel_detail_list=[]

@app.route('/upload',methods=['POST', 'GET'])
def upload():
    file = request.files['file']

    if not file:
        return render_template('index.html', status='null')

    if allow_file(file.filename):
        file.save(os.path.join(app.config['UPLOAD_FOLDER'] + '/upload/', file.filename))
        result_list = mysqldb().read_data()

        for result in result_list:
            detail_dict = {}
            detail_dict['caseid']=result.get('case_id')
            detail_dict['casedesc'] = result.get('case_desc')
            detail_dict['module'] = result.get('case_module')
            detail_dict['batch_info'] = result.get('batch_info')
            Exc_datacollect.Excel_detail_list.append(detail_dict)

        JJxuanran_render3(Exc_datacollect)
        time.sleep(10)
        report_name = render_tem(DataCollect)
        print(report_name)
        return render_template('excel.html', status='OK')


@app.route('/exequte',methods=["GET","POST"])
def do():
    if request.method == "POST":
        docaseid=request.form.get("docaseid")
        suite = unittest.TestSuite()
        caselist = unittest.TestLoader().loadTestsFromModule(testcase_sun)
        suite.addTests(caselist)
        # unittest.TestResult()--运行结果实例化一个对象r
        r = unittest.TestResult()
        # suite执行r的结果
        suite.run(result=r)
        report_name = render_tem(DataCollect)
        return app.send_static_file('Report/'+report_name)

@app.route('/search',methods=["GET","POST"])
def search():
    if request.method == "POST":
        batch_info = request.form.get('batch_info')
        batch_info_list = mysqldb().read_batchinfo()
        report_name = render_tem(DataCollect)
        for batch_number in batch_info_list:
            if batch_info == batch_number.get('batch_info'):
                return app.send_static_file('Report/' + report_name)


if __name__ == '__main__':
    # get_data()
    app.run(debug=True)
